﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using Brain;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Brain.Windows
{
    public partial class VisualScriptControl : GraphicsDeviceControl
    {
        /// <summary>
        /// Timer used for updating and drawing the Engine
        /// </summary>
        public System.Windows.Forms.Timer Timer { get; set; }

        public Stopwatch ElapsedTime { get; set; }
        public Stopwatch TotalTime { get; set; }

        public GameTime GameTime { get; set; }

        public event SetVoid OnDraw;

        public VisualScript VisualScript;
        public Camera2D Camera;

        public VisualScriptControl()
        {
            ElapsedTime = new Stopwatch();
            TotalTime = new Stopwatch();

            TotalTime.Start();

            VisualScript = new VisualScript();
        }

        public SetVoid OnStart;

        protected override void Initialize()
        {
            Timer = new System.Windows.Forms.Timer();
            Timer.Interval = (int)((1f / 60f) * 1000);
            Timer.Tick += new EventHandler(Timer_Tick);
                        
            Mouse.WindowHandle = Handle;

            Camera = new Camera2D();

            base.Initialize();

            Timer.Start();

            if (OnStart != null)
            {
                OnStart();
            }
        }

        protected void Timer_Tick(object sender, EventArgs e)
        {
            // Invalidate everything so the whole control refreshes
            this.Invalidate();

            // Force the view update
            this.Update();
        }

        protected override void Draw()
        {
            UpdateGameTime();
            Engine.Instance.GraphicsDevice.Clear(Color.CornflowerBlue);
            if (OnDraw != null)
            {
                OnDraw();
            }
            
            Camera.Draw();
            VisualScript.Update();
        }

        protected void UpdateGameTime()
        {
            // Recreate the GameTime with the current values
            GameTime = new GameTime(TotalTime.Elapsed, ElapsedTime.Elapsed);

            ElapsedTime.Reset();
            ElapsedTime.Start();
        }
    }
}
